//Service for computer

#include "servicemaster.h"

extern unsigned char UsartRecieveBuf[512];

void memset(unsigned char *buff,unsigned char tem ,unsigned int length)
{
	 unsigned int t;
	 for(t = length;t>0;t--)
	 	*buff++ = tem;
}

void memcpy(unsigned char *Des,unsigned char *Sour ,unsigned int length)
{
	unsigned int i;
	for(i = 0;i<length;i++)
		*Des++ = *Sour++;
}

unsigned char  GetCRC(unsigned char *p)
{
		unsigned char tem=0 , i,k ;
		k = p[0];
		for(i= 0 ;i<k-1;i++)
		{
			tem += p[i];
		}	
			tem = 0xff-tem+1;
		return tem;
}

void UsartSendStr(unsigned char *p)
{
	unsigned char tem,i;
	tem = *p;
	for(i= 0 ;i<tem;i++)
	{	
		USART_SendData(USART1, *p++);	       
		while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
	}
}

unsigned char UsartPro(void)
{
	int temp;//i,
	unsigned char flag;	
	if(GetUsartCount()>1)
	{
		temp =((UsartRecieveBuf[0]<<8)+UsartRecieveBuf[1]);
		if(GetUsartCount()>=temp)
		{
		  /*	 for(i=0;i<temp;i++)
			{
				USART_SendData(USART1, UsartRecieveBuf[i]);	       
		        while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); 
			}
		*/	
			SetUsartCount(0);
			 flag = 1;
		 }
	}
	else 
		flag = 0;
	return flag;
}

unsigned char DataPro(unsigned char *q)
{
	unsigned char rxbuf1[64], *p;
	unsigned char tem;
	p = q;
	p += 2;

	while(*p)
	{
	  tem = *p;
		memcpy(rxbuf1,p,*p);
		if(GetCRC(rxbuf1)!=rxbuf1[tem-1])			
			return 	ReportErr(rxbuf1);
		p += *p;
	}
	return OK;
}

unsigned char ReportErr(unsigned char *p)
{
	return CRCERR;
}

void AckForMaster(unsigned char *p,unsigned char Result)
{
	unsigned char *buffer;
	unsigned char tem[64];
	buffer = p;
	buffer += 3;
	switch(*buffer)
	{
		case 100:
		case 101:
		case 102:	
		case 104:
		case 105:
		case 106: AckFor100(buffer,tem,Result);
							UsartSendStr(tem);
							break;
		
		case 103:
							AckFor103(buffer,tem,Result);
							UsartSendStr(tem);
							break;
							
		default :	break;
	}	
}

void AckFor100(unsigned char *p,unsigned char *tem,unsigned char Result)
{
	unsigned char *buffer,*t;
	
	t = tem;
	buffer = p;
	
	*t = 9;
	t += 1;
	
	*t = *buffer + 128;
	memcpy(t+1,buffer+4,2);
	memcpy(t+3,buffer+1,3);
	*(t+6) =  Result;
	t = tem;
	*(t+8) = GetCRC(t);	
}

void AckFor103(unsigned char *p,unsigned char *tem,unsigned char Result)
{
	tem[0] = 4;
	
	tem[1] = *p+128;
	tem[2] = Result;
	tem[3] = GetCRC(tem); 
}

